package org.apache.hadoop.hdfs.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataEncryptionKeyFactory;
import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.server.datanode.SecureDataNodeStarter.SecureResources;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.security.token.Token;

@InterfaceAudience.Private
public class TcpPeerServer implements PeerServer {
  static final Log LOG = LogFactory.getLog(TcpPeerServer.class);

  private final ServerSocket serverSocket;

  public static Peer peerFromSocket(Socket socket) throws IOException {
    // Peer是对Socket、输入输出流等的封装， 有BasicInetPeer和NioInetPeer两种
    Peer peer = null;
    boolean success = false;
    try {
      // 由于Nagle算法与延迟ACK之间的交互不好，TCP_NODELAY 在这里是至关重要的。
      // 在客户端和DataNode之间保持连接,  会话看起来像:
      //   1. Client -> DataNode: 读取 block X
      //   2. DataNode -> Client: block X的数据
      //   3. Client -> DataNode: 状态 OK （成功读取）
      //   4. Client -> DataNode: 读取 block Y
      // 第3步和第4步都在client->DN方向，这一事实触发了Nagle算法。
      // 如果DataNode使用延迟确认，则会导致40毫秒或更长的延迟。
      //
      // TCP_NODELAY禁用Nagle算法，从而避免了这种性能灾难。
      socket.setTcpNoDelay(true); // 设置TCP无延迟
      SocketChannel channel = socket.getChannel(); // 获得SocketChannel

      // Peer是对Socket、输入输出流等的封装，有BasicInetPeer和NioInetPeer两种

      // 利用socket创建peer，如果通道channel为null，则创建基本的BasicInetPeer，否则创建NioInetPeer
      if (channel == null) {
        // BasicInetPeer代表了基本的Peer，封装了Socket、OutputStream、InputStream三者
        peer = new BasicInetPeer(socket);
      } else {
        // NioInetPeer代表了一种可通过使用非阻塞IO进行Socket通讯的一种Peer，封装了Socket、SocketInputStream、SocketOutputStream三者
        peer = new NioInetPeer(socket);
      }
      // 标志位success设置为true
      success = true;
      return peer;
    } finally {
      if (!success) { // 如果创建不成功，peer不为空的话，关闭之
        if (peer != null) {
          peer.close();
        }
        // 关闭socket
        socket.close();
      }
    }
  }

  public static Peer peerFromSocketAndKey(
        SaslDataTransferClient saslClient, Socket s,
        DataEncryptionKeyFactory keyFactory,
        Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId)
        throws IOException {
    Peer peer = null;
    boolean success = false;
    try {
      peer = peerFromSocket(s);
      peer = saslClient.peerSend(peer, keyFactory, blockToken, datanodeId);
      success = true;
      return peer;
    } finally {
      if (!success) {
        IOUtils.cleanup(null, peer);
      }
    }
  }

  /**
   * Create a non-secure TcpPeerServer.
   *
   * @param socketWriteTimeout    The Socket write timeout in ms.
   * @param bindAddr              The address to bind to.
   * @param backlogLength         The length of the tcp accept backlog
   * @throws IOException
   */
  public TcpPeerServer(int socketWriteTimeout,
                       InetSocketAddress bindAddr,
                       int backlogLength) throws IOException {
    this.serverSocket = (socketWriteTimeout > 0) ?
          ServerSocketChannel.open().socket() : new ServerSocket();
    Server.bind(serverSocket, bindAddr, backlogLength);
  }

  /**
   * Create a secure TcpPeerServer.
   *
   * @param secureResources   Security resources.
   */
  public TcpPeerServer(SecureResources secureResources) {
    this.serverSocket = secureResources.getStreamingSocket();
  }
  
  /**
   * @return     the IP address which this TcpPeerServer is listening on.
   */
  public InetSocketAddress getStreamingAddr() {
    return new InetSocketAddress(
        serverSocket.getInetAddress().getHostAddress(),
        serverSocket.getLocalPort());
  }

  @Override
  public void setReceiveBufferSize(int size) throws IOException {
    this.serverSocket.setReceiveBufferSize(size);
  }

  @Override
  public Peer accept() throws IOException, SocketTimeoutException {
    Peer peer = peerFromSocket(serverSocket.accept()); //
    return peer;
  }

  @Override
  public String getListeningString() {
    return serverSocket.getLocalSocketAddress().toString();
  }
  
  @Override
  public void close() throws IOException {
    try {
      serverSocket.close();
    } catch(IOException e) {
      LOG.error("error closing TcpPeerServer: ", e);
    }
  }

  @Override
  public String toString() {
    return "TcpPeerServer(" + getListeningString() + ")";
  }
}
